package com.bbx.demo.protobuf;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import lombok.extern.slf4j.Slf4j;

import java.util.Random;

@Slf4j
public class ProtobufClientHandler extends SimpleChannelInboundHandler<DataInfoTest.DataInfo> {
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, DataInfoTest.DataInfo msg) throws Exception {
        DataInfoTest.DataInfo.DataType dataType = msg.getDataType();
        if (dataType == DataInfoTest.DataInfo.DataType.persion_type) {
            DataInfoTest.Student student = msg.getStudent();
            log.info("Name[{}]", student.getName());
            log.info("Age[{}]", student.getAge());
            log.info("Address[{}]", student.getAddress());
        }
        if (dataType == DataInfoTest.DataInfo.DataType.dog_type) {
            DataInfoTest.Dog dog = msg.getDog();
            log.info("Name[{}]", dog.getName());
            log.info("Age[{}]", dog.getAge());
        }
        if(dataType == DataInfoTest.DataInfo.DataType.cat_type) {
            DataInfoTest.Cat cat = msg.getCat();
            log.info("City[{}]", cat.getCity());
            log.info("Age[{}]", cat.getName());
        }
    }


    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        int i = new Random().nextInt(3);
        DataInfoTest.DataInfo build = null;
        switch (i){
            case 0:
                build = DataInfoTest.DataInfo.newBuilder()
                        .setDataType(DataInfoTest.DataInfo.DataType.persion_type)
                        .setStudent(
                                DataInfoTest.Student.newBuilder()
                                        .setName("HAHA")
                                        .setAge(30)
                                        .setAddress("天津")
                                        .build()
                        ).build();
                break;
            case 1:
                build = DataInfoTest.DataInfo.newBuilder()
                        .setDataType(DataInfoTest.DataInfo.DataType.dog_type)
                        .setDog(
                                DataInfoTest.Dog.newBuilder()
                                        .setName("狗")
                                        .setAge(2)
                                        .build()
                        ).build();
                break;
            case 2:
                build = DataInfoTest.DataInfo.newBuilder()
                        .setDataType(DataInfoTest.DataInfo.DataType.cat_type)
                        .setCat(
                                DataInfoTest.Cat.newBuilder()
                                        .setName("猫")
                                        .setCity("上海")
                                        .build()
                        ).build();
                break;
        }

        ctx.writeAndFlush(build);
    }
}
